<?php
class insertdata extends CI_Controller{
	
	private $view_data = array();
	
	function __construct(){
		parent::__construct();
	}
	
##################################################################################################################################	
	//this function adds the property company data
	function addpropcompany(){

		$this->load->library('form_validation');
		
		//setting cutom validation errors
		$this->form_validation->set_message('required', '%s cannot be empty');
		$this->form_validation->set_message('min_length', '%s should be at least %s characters');
		$this->form_validation->set_message('max_length', '%s should be less than %s characters');
		$this->form_validation->set_message('alpha_numeric', '%s should be in alpha-numeric characters');
		$this->form_validation->set_message('exact_length', '%s should be exactly %s characters long');
		$this->form_validation->set_message('valid_email', '%s should be a valid email address');
		
		//setting validation rules
		$this->form_validation->set_rules('company_name', 'Company name', 'required|xss_clean|min_length[10]|max_length[45]');
		$this->form_validation->set_rules('company_display_name', 'Display name', 'required|xss_clean|min_length[10]|max_length[25]');
		$this->form_validation->set_rules('company_address', 'Company address', 'required|xss_clean');
		$this->form_validation->set_rules('company_tp', 'Company telephone', 'required|xss_clean|exact_length[10]');
		$this->form_validation->set_rules('company_email', 'Company email', 'required|xss_clean|valid_email|max_length[45]');
		
		if($this->form_validation->run() != false){
			
			$this->load->model('insertdata_model');
			$query = 'INSERT INTO property_companies (company_name,company_display_name,company_address,company_telephone,company_email)
						VALUES (?,?,?,?,?)';
			$params = array($this->input->post('company_name'),
							$this->input->post('company_display_name'),
							$this->input->post('company_address'),
							$this->input->post('company_tp'),
							$this->input->post('company_email'));
			
			/*insert the post data to the database and get the inserted company id.
			 * after retrieving the company id, need to echo it along with the 'company_display_name' as a json object*/
			$company_id = $this->insertdata_model->insertdata(true,$query,$params);
			$output = '{"validation_result": "'.$company_id.'", "new_company_display_name": "'.$this->input->post('company_display_name').'"}';
			echo $output;
		}
		
		else{
			
			//if validation error happens, we need to echo it as a json object
			$output = '{ "company_name": "'.form_error('company_name').'",
						"company_display_name": "'.form_error('company_display_name').'",
						"company_address": "'.form_error('company_address').'",
						"company_tp": "'.form_error('company_tp').'",
						"company_email": "'.form_error('company_email').'"
						}';
			echo $output;
		}
		
	}
	
##################################################################################################################################
	//this function adds the property data
	function addprop(){
		$this->load->library('DataEntryForms');
		if($this->input->post()){
			$form_name = $this->input->post('form_name');
			switch ($form_name)
			{
				case 1:
					$this->dataentryforms->form1();
					break;
				case 2:
					$this->dataentryforms->form2();
					break;
				case 3:
					$this->dataentryforms->form3();
					break;
				case 4:
					$this->dataentryforms->form4();
					break;
				case 5:
					$this->dataentryforms->form5();
					break;
				case 6:
					$this->dataentryforms->form6();
					break;
				case 7:
					$this->dataentryforms->form7();
					break;
				case 7:
					$this->dataentryforms->form8();
					break;
			}
		}
		
		else{
			//pass the required data to the view
			$this->load->model('getdata_model');
			$this->view_data['prop_owners'] = $this->getdata_model->get_prop_owners();
			$this->load->view('dataentry_terminal',$this->view_data);
		}
		
	}
	
	
	
#######################################################################################
	//this function load the ui for adding geo location data
	function addgeo(){
	
		if($this->input->post()){
				
			$this->load->library('form_validation');
				
			//validate the form & save to the database
			$this->form_validation->set_rules('lat', 'Latitude', 'required|decimal|xss_clean');
			$this->form_validation->set_rules('lon', 'Longitude', 'required|decimal|xss_clean');
			$this->form_validation->set_rules('propertyid','propertyid', 'required|integer|xss_clean');
	
			if($this->form_validation->run() != false){
				$this->load->model('insertdata_model');
				$params = array($this->input->post('propertyid'),
						$this->input->post('lon'),
						$this->input->post('lat'),
						$this->input->post('color'));
	
				$query = 'INSERT INTO property_geodata
				(project_id,longitude,latitude,color_code)
				VALUES(?,?,?,?)';
	
				//$propertyid = $this->insertdata_model->insertdata(false,$query,$params);
				
								
				//this code checks whether the color is already exists or not......
				$this->load->model('getdata_model');
				$col = $this->input->post('color');
				
				$color_result = $this->getdata_model->is_exsiting_color('color_code', $col);
				if($color_result!=FALSE){
					//echo 'er';
					$status = "color_exist";
				}
				else{
					$propertyid = $this->insertdata_model->insertdata(false,$query,$params);
					//echo 'sucu';
					$status = "success";
				}
				
			}
			
	
			else {
				
				$status="error";
				//echo 'error';
				
			}
			$output = '{ "status":"'.$status.'", "propertyid": "'.form_error('propertyid').'"}';
			//$output = '{ "lon_error": "'.$lon_error.'", "lat_error": "'.$lat_error.'","status_error":"'.$status.'","msg":"'.$msg.'"}';
			echo $output;
		}
	
		else{
			//echo 'post not present';
			//die();
			$this->load->model('getdata_model');
			$this->view_data['property_id'] = $this->getdata_model->get_geo_missed_propids();
			$this->load->view('addgeodata',$this->view_data);
				
		}
			
	}
	################################################################################################################
	//this function checks color_code
	function color_check()
	{
		$color_array[]=array();
		$this->load->view('addgeodata',$this->view_data);
		//$this->input->post('color');
		
		$this->load->model('getdata_model');
		$this->color_array[]=$this->getdata_model->is_exsiting_color();
		foreach ($color_array as $value){
			if($value==$this->input->post('color')){
				//$this->form_validation->set_message('color_check', 'This color already exists. Please select another color');
				return FALSE;
			}
			else
			{
			
				return TRUE;
			
			}
		}
		
	
	
	}
	
#######################################################################################
	//this function handles the image uplaods
	function do_upload()
	{
		$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '0';
		$config['max_width']  = '0';
		$config['max_height']  = '0';
	
		$this->load->library('upload', $config);
	
		if ( ! $this->upload->do_upload('userfile'))
		{
			$msg = $this->upload->display_errors('','');
			$status = 'error';
			$lat = '';
			$lon = '';
			
		}
		else
		{
			$data = $this->upload->data();
			$exif = exif_read_data('./uploads/'.$data['orig_name'],0,true);
			unlink($data['full_path']);
			if(isset($exif['GPS']["GPSLongitude"]) && $exif['GPS']["GPSLatitude"]){
				$lon = $this->getGps($exif['GPS']["GPSLongitude"], $exif['GPS']['GPSLongitudeRef']);
				$lat = $this->getGps($exif['GPS']["GPSLatitude"], $exif['GPS']['GPSLatitudeRef']);
				$status =  'success';
				$msg = '';
			}
			
			else{
				$status =  'nogeo';
				$msg = "no geo data found";
				$lat = '';
				$lon = '';
			}
		}
		
		$output = '{ "status": "'.$status.'", "msg": "'.$msg.'", "lat": "'.$lat.'", "lon": "'.$lon.'" }';
		echo $output;
	}

######################################################################################################	
	function getGps($exifCoord, $hemi) {
	
		$degrees = count($exifCoord) > 0 ? $this->gps2Num($exifCoord[0]) : 0;
		$minutes = count($exifCoord) > 1 ? $this->gps2Num($exifCoord[1]) : 0;
		$seconds = count($exifCoord) > 2 ? $this->gps2Num($exifCoord[2]) : 0;
	
		$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
	
		return floatval($flip * ($degrees +($minutes/60)+($seconds/3600)));
	
	}

#######################################################################################	
	function gps2Num($coordPart) {
	
		$parts = explode('/', $coordPart);
	
		if (count($parts) <= 0)
			return 0;
	
		if (count($parts) == 1)
			return $parts[0];
	
		return floatval($parts[0]) / floatval($parts[1]);
	}
#######################################################################################	
	function addcompanydata()
	{
		
		echo "20";
		
		//this is error message
		/*
		$companynameerror = "asasasas";
		$displaynameerror = "";
		$addresserror = "asasasa";
		$emailaddresserror = "";
		$tperror = "asafffff";
		
		echo $companynameerror.",,,".$displaynameerror.",,,".$addresserror.",,,".$emailaddresserror.",,,".$tperror.",,,";*/
	}	
}